import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
import { UpOutline, DownOutline } from 'antd-mobile-icons';
import bem from '@/utils/bem';
import classNames from 'classnames';
import { MenuContext, MenuContextProps, MenuCallback, OptionItem } from './context';
import './menu.scss';
import MenuItem from './menu-item';

export interface MenuProps {
    // 选项的选中态图标颜色	
    activeColor: string;
    // 滚动后是否固定，可设置固定位置
    scrollFixed: boolean;
    // 是否在点击外部区域后自动隐藏
    closeOnClickAway: boolean;
    children?: React.ReactNode;
    // 展开menu时触发
    onOpen?: MenuCallback;
    // 关闭menu时触发
    onClose?: MenuCallback;
    onChange?: (v: any) => void;
}
const Menu: React.FC<MenuProps> & { Item: typeof MenuItem } = (props) => {
    const {
        activeColor,
        scrollFixed,
        closeOnClickAway,
        children,
        onOpen,
        onClose,
        onChange,
        ...rest
    } = props;

    const b = bem('menu');
    const childArray = React.Children.toArray(children);
    const childCount = React.Children.count(children);

    // 菜单状态
    const [showMenuItem, setShowMenuItem] = useState<boolean[]>(
        Array(childCount).fill(false)
    );

    // 当前选中的菜单索引
    const [activeIndex, setActiveIndex] = useState<number>(-1);

    const [menuItemTitle, setMenuItemTitle] = useState<string[]>([]);

    const toggleMenuHandler = useCallback((value: { index: number, options?: OptionItem[], defaultOption?: OptionItem }) => {
        const { index, options, defaultOption } = value;
        setShowMenuItem(prev => {
            const newState = prev.map((item, i) =>
                i === index ? !item : false
            );
            const wasOpen = prev[index];
            if (!wasOpen) {
                onOpen?.(index);
            } else {
                onClose?.(index);
            }
            return newState;
        }
        );
        setActiveIndex(prev => prev === index ? 0 : index);
        // 获取默认选项
        if (!options || options.length === 0) {
            // onChange?.(defaultOption);
            onChange?.(defaultOption);
        }
    }, []);

    const hideMenuHandler = useCallback((index: number) => {
        setShowMenuItem(prev => {
            return prev.map((item, i) => i === index ? false : item);
        });
        setActiveIndex(prev => prev === index ? -1 : prev);
    }, []);


    // 获取标题
    const finalTitle = (index: number) => {
        if (menuItemTitle && menuItemTitle[index]) {
            return menuItemTitle[index];
        } else {
            const child = childArray[index];
            if (React.isValidElement(child)) {
                return child.props?.defaultOption?.text;
            }
            return '';
        }
    }

    const contextValue = useMemo(() => ({
        showMenuItem,
        activeIndex,
        toggleMenuHandler,
        // 更新标题
        updateTitle: (index: number, title: string) => {
            setMenuItemTitle(prev => {
                const newState = [...prev];
                newState[index] = title;
                return newState;
            });
        },
        hideMenuHandler,
    }), [showMenuItem, activeIndex, toggleMenuHandler]);

    return (
        <MenuContext.Provider value={contextValue}>
            <div className={b()}>
                <div className={b('bar')}>
                    {
                        childArray.map((child, index) => {
                            if (!React.isValidElement(child)) {
                                return null;
                            }
                            const options = child.props.options || [];
                            const defaultOption = child.props.defaultOption;

                            const menuValue = {
                                index,
                                options,
                                defaultOption
                            };

                            const isOpen = showMenuItem[index];
                            return (
                                <div className={b('bar__item')} key={index} onClick={() => toggleMenuHandler(menuValue)}>
                                    <div className={classNames(b('bar__item-title'))} >
                                        {finalTitle(index)}
                                    </div>
                                    {
                                        options && options.length > 0 && (
                                            <span >
                                                {
                                                    isOpen ? <UpOutline /> : <DownOutline />
                                                }
                                            </span>
                                        )
                                    }
                                </div>
                            );
                        })
                    }

                </div>

                {
                    childArray?.map((child, i) => {
                        if (!React.isValidElement(child)) {
                            return null;
                        }
                        const options = child.props.options || [];
                        return (
                            <MenuItem
                                key={i}
                                options={options}
                                itemIndex={i}
                                showItem={showMenuItem[i]}
                                onChange={onChange}
                            />
                        );
                    })
                }
            </div>

        </MenuContext.Provider>
    )
}

Menu.Item = MenuItem;

export default Menu;